package ca.etsmtl.cours.log735.lab3.client;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.io.Serializable;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

public class BankBranch extends Thread implements IBankBranch, Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = -3739816589091751457L;
	private List<IBankBranch> otherBranches;
	private int currentMoneyAmount;
	private boolean isSendingMoney;
	public static int PORT = 15000;
	private String bankIp;
	private transient Socket clientSocket;
	private transient ServerSocket serverSocket;
	private transient PrintWriter printWriter;
	private transient BufferedInputStream bufferedReader; //non serializable
	private transient ObjectOutputStream objectOutputStream;
	private int clientId;
	
	public BankBranch(int clientId, String bankIp, int currentMoneyAmount){
		otherBranches = new ArrayList<IBankBranch>();
		isSendingMoney = false;
		this.clientId = clientId;
		this.bankIp = bankIp;
		this.currentMoneyAmount = currentMoneyAmount;
	}
	
	@Override
	public void run(){
		try {
			clientSocket = new Socket(bankIp, PORT);
			printWriter = new PrintWriter(clientSocket.getOutputStream(),true);
			bufferedReader = new BufferedInputStream(clientSocket.getInputStream());
			objectOutputStream = new ObjectOutputStream(clientSocket.getOutputStream());
			
			System.out.println("Notifying bank of my presence .. " + clientId);
			objectOutputStream.writeObject(this);
			//printWriter.write("INITIAL-MONEY-AMOUNT:"+currentMoneyAmount);
			Thread.sleep(10000);
			System.out.println(otherBranches);
			Thread.sleep(30000);
			bufferedReader.close();
			printWriter.close();
			clientSocket.close();
			objectOutputStream.close();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void sendMoney(IBankBranch branch, int moneyAmountToSend) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public int getCurrentMoney() {
		// TODO Auto-generated method stub
		return 0;
	}

	public List<IBankBranch> getOtherBranches() {
		return otherBranches;
	}

	public void setOtherBranches(List<IBankBranch> otherBranches) {
		this.otherBranches = otherBranches;
	}

	public int getClientId() {
		return clientId;
	}

	public void setClientId(int clientId) {
		this.clientId = clientId;
	}

	public ServerSocket getServerSocket() {
		return serverSocket;
	}

	public void setServerSocket(ServerSocket serverSocket) {
		this.serverSocket = serverSocket;
	}

}
